<template>
	<view class="position-absolute-cover over-hidden">
		<com-scan ref="scan" :auto="false" @ready="handleReady" @scaned="handleScaned" @destroyed="handleDestroyed" />
		<view class="position-absolute top-0 left-0 right-0">
			<com-status-bar></com-status-bar>
			<view class="y-flex y-row y-align-center y-justify-between page-padding-gap" style="height: 100rpx;">
				<com-icon name="round_close_fill" size="50" color="#fff" @click="back"></com-icon>
				<com-icon name="album" size="50" color="#fff" @click="chooseImage"></com-icon>
			</view>
		</view>
	</view>
</template>

<script>
	import { requestPermissions } from '@/assets/js/native.js'
	export default {
		data () {
			return {
				result: null
			}
		},
		methods: {
			handleReady () {
				//需要先获取摄像头权限，否则无法获取到摄像头
				requestPermissions({
					permissions: ['android.permission.CAMERA'],
					message: '扫码功能需要开启摄像头',
					success: () => {
						this.$refs.scan.start()
					},
					fail: (err) => {
						uni.showToast({
							title: '获取摄像头权限失败，扫码功能无法使用',
							icon: 'none'
						})
					}
				})
			},
			handleScaned (e) {
				this.result = e
				this.back()
			},
			back () {
				this.$refs.scan.stop()
			},
			chooseImage () {
				this.$refs.scan.album()
			},
			handleDestroyed () {
				uni.navigateBack({
					success: () => {
						if ( this.result ) uni.$emit('scaned', this.result)
						else uni.$off('scaned')
					}
				})
			}
		},
		onBackPress(event) {
			if ( event.from == 'backbutton' ) {
				this.$refs.scan.stop()
				return true
			}
			return false
		}
	}
</script>

<style>
</style>